package org.theSeed.base.utils;

import cn.hutool.core.util.ObjectUtil;
import org.theSeed.base.contract.DbRecordInterface;
import org.theSeed.base.pojo.po.RecordDatePo;
import org.theSeed.base.pojo.po.RecordUserAndDatePo;
import org.theSeed.base.pojo.po.RecordUserPo;

import java.util.Date;
import java.util.function.Supplier;

/**
 * 数据库po工具
 */
public class PoUtil {
    /**
     * 获取用户主键信息
     */
    private static Supplier<String> getUserKey;


    /**
     * 更新初始化
     * @param dbRecordInterface
     */
    public static void updateInit(DbRecordInterface dbRecordInterface){
        updateInit(dbRecordInterface,new Date());
    }

    /**
     * 插入初始化
     * @param dbRecordInterface
     */
    public static void insertInit(DbRecordInterface dbRecordInterface){
        insertInit(dbRecordInterface,new Date());
    }



    /**
     * 更新初始化
     */
    public static void updateInit(DbRecordInterface dbRecordInterface, Date date){
        if (ObjectUtil.isNull(dbRecordInterface)){
            return;
        }

        if (dbRecordInterface instanceof RecordDatePo){
            RecordDatePo record = (RecordDatePo) dbRecordInterface;
            record.setUpdateTime(date);
        }
        else if (dbRecordInterface instanceof RecordUserPo){
            RecordUserPo record = (RecordUserPo) dbRecordInterface;
            if (ObjectUtil.isNotNull(date))
                record.setUpdateUser(getUserKey.get());
        } else if (dbRecordInterface instanceof RecordUserAndDatePo){
            RecordUserAndDatePo record = (RecordUserAndDatePo) dbRecordInterface;
            record.setUpdateTime(date);
            if (ObjectUtil.isNotNull(date))
                record.setUpdateUser(getUserKey.get());
        }
    }

    /**
     * 创建初始化
     */
    public static void insertInit(DbRecordInterface dbRecordInterface,Date date){
        if (ObjectUtil.isNull(dbRecordInterface)){
            return;
        }

        if (dbRecordInterface instanceof RecordDatePo){
            RecordDatePo record = (RecordDatePo) dbRecordInterface;
            record.setCreateTime(date);
            record.setUpdateTime(date);
        }
        else if (dbRecordInterface instanceof RecordUserPo){
            RecordUserPo record = (RecordUserPo) dbRecordInterface;
            if (ObjectUtil.isNotNull(date)){
                String user = getUserKey.get();
                record.setCreateUser(user);
                record.setUpdateUser(user);
            }
        } else if (dbRecordInterface instanceof RecordUserAndDatePo){
            RecordUserAndDatePo record = (RecordUserAndDatePo) dbRecordInterface;
            record.setCreateTime(date);
            record.setUpdateTime(date);
            if (ObjectUtil.isNotNull(date)){
                String user = getUserKey.get();
                record.setCreateUser(user);
                record.setUpdateUser(user);
            }
        }
    }
}
